<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyOrtherProductTable;
use App\Http\Repository\OmsRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class pullJyItem extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pullJyItem {--skuCodes=} {--productCodes=}';

    /**
     * The console command description.
     * 0 0,12 * * *
     * @var string
     */
    protected $description = '拉取巨益商品信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $autoKey = "auto_pullJyItem";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $skuCodes = $this->option('skuCodes') ?: "";
        $productCodes = $this->option('productCodes') ?: "";
        $skuCodes = !empty($skuCodes) ? explode(",", $skuCodes) : "";
        $productCodes = !empty($productCodes) ? explode(",", $productCodes) : "";
        $totalPage = 1;
        $limit = 20;
        for($page = 1; $page <= $totalPage; $page++){
            $res = OmsRepository::searchItem($page, $limit, $skuCodes, $productCodes);
            if(!isset($res['data']) || empty($res['data'])){
                echo "没有发现数据\n";
                break;
            }
            if($page == 1){
                $totalPage = ceil($res['total']/$limit);
            }
            $this->setData($res['data'], $page, $totalPage);
        }
        Cache::forget($autoKey);
        //删除未同步更新的巨益商品信息数据
        $total = (new SsyJyProductListTable())->where('updatetime', '<', date('Y-m-d 00:00:00'))->count();
        if($total > 0 && $total < 100){
            (new SsyJyProductListTable())->deleteDataWhere(['updatetime' => ['<' => date('Y-m-d 00:00:00')]]);
            echo "删除未同步更新的巨益商品信息数据： {$total}条\n";
        }
    }

    public function setData($list, $page, $totalPage)
    {
        foreach ($list as $item){
            if(!isset($item['brandCode'])){
                continue;
            }
            $num = 1;
            $totalNum = count($item['skus']);
            $createTime = date('Y-m-d H:i:s');
            foreach ($item['skus'] as $skuItem){
                echo "第[{$totalPage}, {$page}]页, 正在执行, 明细：{$totalNum} / {$num}, sku：{$skuItem['skuCode']}\n";
                $num++;
                //如果是物料或者赠品
                if(isset($item['productCategoryName']) && in_array($item['productCategoryName'], ["物料", "赠品"])){
                    if(is_array($item['productCode'])){
                        $size_code=serialize($item['productCode']);
                    }else{
                        $size_code = $item['productCode'] ?? "";
                    }
                    $existOrther = (new SsyOrtherProductTable())->where('sku_code', $size_code)->where('type_no', $item['productCode'])->first();
                    if(empty($existOrther)){
                        $saveData = [
                            "type_no"=>$item['productCode'],
                            "type_name"=>$item['productName'],
                            "size_code"=>$size_code,
                            "sku_code"=>$size_code,
                            "image" => $skuItem['skuImage'] ?? "",
                            "brand"=>$item['brandName'] ?? "",
                            "attribute"=>$item['productCategoryName'] ?? "",
                            "volume"=>$skuItem['volume'] ?? "",
                            "basic_price"=>$skuItem['sellingPrice'] ?? "",
                            "createtime"=>$createTime
                        ];
                        (new SsyOrtherProductTable())->createData($saveData);
                    }
                }
                $jyImage = $skuItem['skuImage'] ?? ($item['imageUrl'] ?? "");//sku没有图片 用主图
                $existJy = (new SsyJyProductListTable())->where('product_code', $skuItem['skuCode'])->where('type_no', $item['productCode'])->first();
                if(empty($existJy)){
                    $data = [
                        "brand_code"=>$item['brandCode'],
                        "brand_name"=>$item['brandName'],
                        "num"=>$skuItem['quantity'] ?? 0,
                        "commodity_classification"=>$item['productCategoryName'] ?? "",
                        "a_num" => $skuItem['quantity'] ?? 0,
                        "type_no"=>$item['productCode'],
                        "product_code"=>$skuItem['skuCode'],
                        "product_name"=>$skuItem['productName'],
                        "selling_price"=>$skuItem['sellingPrice'],
                        "tag_price" => $skuItem['markedPrice'],
                        "cost_price" => $skuItem['costPrice'],
                        "last_date"=>$item['listingYear'],
                        "a_parts"=>$skuItem['skuName'],//规格名称
                        "product_size" => $skuItem['size'] ?? "",
                        "createtime" => $createTime,
                        "updatetime" => $createTime,
                        "img" => $jyImage
                    ];
                    (new SsyJyProductListTable())->createData($data);
                }else{
                    $data = [
                        "brand_code"=>$item['brandCode'],
                        "brand_name"=>$item['brandName'],
                        "product_name" => $skuItem['productName'],
                        "a_parts" => $skuItem['skuName'],
                        "product_size" => $skuItem['size'] ?? "",
                        "commodity_classification" => $item['productCategoryName'] ?? "",
                        "img" => $jyImage,
                        "selling_price" => $skuItem['sellingPrice'],
                        "tag_price" => $skuItem['markedPrice'],
                        "cost_price" => $skuItem['costPrice'],
                        "updatetime" => $createTime
                    ];
                    (new SsyJyProductListTable())->updateData($existJy->id, $data);
                }
            }
        }
    }
}
